<?php

namespace App\Http\Middleware;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Common\Enum\CommonCodeEnum;
use App\Kuafu\Common\Exceptions\CommonException;
use App\Kuafu\Shop\Exceptions\ShopException;
use App\Kuafu\Shop\Service\ShopService;
use App\Kuafu\User\Enum\UserCodeEnum;
use App\Kuafu\User\Exceptions\AuthException;
use App\Kuafu\User\Exceptions\UserException;
use App\Kuafu\User\Service\AuthService;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class MerchantBrandShop
{
    /**
     * 商家APP - 校验品牌，切换店铺
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     * @throws BaseException
     * @throws CommonException
     * @throws UserException
     * @throws AuthException
     */
    public function handle(Request $request, Closure $next)
    {
        $shopId  = (int)$request->header('shopId');
        $brandId = (int)$request->header('brandId');

        // 开发环境免认证
        if (config('app.env') == 'dev') {
            $brandId = $brandId ?: 1;
            $shopId  = $shopId ?: 1;
        }

        if (empty($brandId) || !is_numeric($brandId)) {
            throw new CommonException(CommonCodeEnum::ERR_BRAND_ID_ERROR);
        }

        if (empty($shopId) || !is_numeric($shopId)) {
            throw new UserException(UserCodeEnum::ERR_PMS_USER_NOT_IN_SHOP);
        }

//        $payload = AuthService::getPayload()->toArray();
//        $isStaff = isset($payload["thirdLoginType"]) && $payload["thirdLoginType"];
//        if (!$isStaff) {
//
//            $shopIds  = UserRoleMapping::getShopListByUserIdCache($userInfo->id, CodeEnum::PLATFORM_BUSINESS);
//            if (!in_array($shopId, $shopIds) && config('app.env') != 'dev') {
//                throw new BaseException(BaseCodeEnum::ERR_NO_ACCESS);
//            }
//        }

        $payload  = AuthService::getPayload()->toArray();
        $userInfo = AuthService::getAuthUser();

        if (config('app.env') != 'dev' || $shopId !== 0) {

            //员工门店鉴权
            $this->checkShopAccess($payload, $shopId, $userInfo->id);
        }

        return $next($request);
    }


    /**
     * 员工门店鉴权
     *
     * @param array $payload
     * @param int $shopId
     * @param int $uid
     * @throws BaseException
     * @throws UserException
     * @throws ShopException
     */
    public function checkShopAccess(array $payload, int $shopId, int $uid)
    {
        $isStaff = isset($payload["thirdLoginType"]) && $payload["thirdLoginType"];

        $check = Cache::remember("checkShopAccess:{$uid}:{$shopId}:{$isStaff}", 30, function () use ($uid, $isStaff, $shopId) {
            return ShopService::shopListDb($uid, $isStaff, '', $shopId, 0, 1, 1, ['id']);
        });

        if (count($check) == 0) {
            throw new BaseException(BaseCodeEnum::ERR_NO_ACCESS);
        }
    }
}
